package com.xx.app.config.jwt.utils;


import com.auth0.jwt.exceptions.TokenExpiredException;
import com.xx.app.vo.AppLoginUser;
import com.xx.common.constant.CacheConstants;
import com.xx.common.core.redis.RedisCache;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Data
@Component
public class UserUtils {

    private static RedisCache redisCache;

    @Autowired
    public UserUtils(RedisCache redisCache) {
        UserUtils.redisCache = redisCache;
    }

    @PostConstruct
    public void initializeUID() {
        if (!redisCache.hasKey(CacheConstants.UID_KEY)) {
            log.info("Initialize UID");
            redisCache.setCacheObject(CacheConstants.UID_KEY, CacheConstants.INITIAL_VALUE);
        }
    }

    public static AppLoginUser getAppLoginUser() {
        Object object = redisCache.getLoginUserByAddress(JwtUtils.getAddress());
        if (object != null) {
            return (AppLoginUser) object;
        }
        throw new TokenExpiredException("token.expired");
    }

}
